/*
 * 版权所有 2009-2022山东新北洋信息技术股份有限公司 保留所有权利。
 */
package online.xuping.thousandsOfWorlds.common.importexcel.strategy;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import online.xuping.thousandsOfWorlds.common.exception.BusinessRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.lang.reflect.Field;
import java.util.Set;

/**
 * 参数校验的service
 *
 * @author yujian
 * @date 2022/8/25 10:49
 * @copyright 2022 山东新北洋信息技术股份有限公司. All rights reserved
 */
@Slf4j
@Service
public class ParamCheckServiceImpl {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 对传入的注解进行校验
     *
     * @param obj : 传入需要校验的对象
     * @return {@link String } 返回错误信息
     * @author yujian
     * @date 2022/8/27 14:36
     **/
    public static <T> String validateEntity(T obj) throws NoSuchFieldException {
        StringBuilder result = new StringBuilder();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (!set.isEmpty()) {
            for (ConstraintViolation<T> cv : set) {
                Field declaredField = obj.getClass().getDeclaredField(cv.getPropertyPath().toString());
                ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
                log.info("获取的Excel的列表的信息为{}", annotation);
                result.append(cv.getMessage()).append(";");
            }
        }
        return result.toString();
    }

    public static <T> void validRes(T obj) throws NoSuchFieldException {
        String errorMessage = validateEntity(obj);
        if (StrUtil.isNotBlank(errorMessage)) {
            throw new BusinessRuntimeException(errorMessage);
        }

    }

}
